package interview.sort;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description: 希尔排序
 * User: xxm
 * Date: 2018-04-08
 * Time: 23:30
 */
public class ShellSort {

    public static int[] shellSort(int[] array) {
        if (array.length == 0) {
            return array;
        }

        // 数组长度,用于计算shell增量
        int len = array.length;
        // 中间变量
        int temp = len / 2;
        // shell增量
        int increment = len / 2;

        // 不断减少增量
        while (increment > 0) {
            // 分组执行插入排序
            for (int i = increment; i < len; i++) {
                // 执行分组，组前元素
                temp = array[i];
                // 组后元素
                int preIndex = i - increment;
                // 分组中排在前面的元素大于后面的，
                while (preIndex >= 0 && array[preIndex] > temp) {
                    // 则将排在前面的元素插入到后面元素的位置上
                    array[preIndex + increment] = array[preIndex];
                    preIndex -= increment;
                }
                // 将排在后面元素插入到前面
                array[preIndex + increment] = temp;
            }
            // 减少shell增量
            increment /= 2;
        }
        return array;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(
                ShellSort.shellSort(new int[]{0, -1, 2, -5, -20, -10})
        ));

        System.out.println(Arrays.toString(
                ShellSort.shellSort(new int[]{})
        ));

        System.out.println(Arrays.toString(
                ShellSort.shellSort(new int[]{4, 4, 4})
        ));

        System.out.println(Arrays.toString(
                ShellSort.shellSort(new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9})
        ));

        System.out.println(Arrays.toString(
                ShellSort.shellSort(new int[]{9, 8, 7, 6, 5, 4, 3, 2, 1})
        ));

        System.out.println(Arrays.toString(
                ShellSort.shellSort(new int[]{31, 50, 12, 44, 2, 55, 78, 43, 24})
        ));
    }

}
